"""
题目：计算二叉树中所有节点的总数。
"""


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def count_nodes(node):
    """计算二叉树中节点的总数（递归实现）"""
    # 空节点没有节点，返回0
    if not node:
        return 0
    # 节点总数 = 1（当前节点） + 左子树节点数 + 右子树节点数
    return 1 + count_nodes(node.left) + count_nodes(node.right)


# 辅助函数：创建二叉树（复用）
def create_binary_tree(arr):
    if not arr:
        return None
    root = TreeNode(arr[0])
    queue = [root]
    index = 1
    while queue and index < len(arr):
        current = queue.pop(0)
        if arr[index] is not None:
            current.left = TreeNode(arr[index])
            queue.append(current.left)
        index += 1
        if index < len(arr) and arr[index] is not None:
            current.right = TreeNode(arr[index])
            queue.append(current.right)
        index += 1
    return root


# 测试
root1 = create_binary_tree([1, 2, 3, 4, 5, 6])
print(count_nodes(root1))  # 输出: 6

root2 = create_binary_tree([])  # 空树
print(count_nodes(root2))  # 输出: 0
